# zennotac-backend/app/routes/ocr.py
from fastapi import APIRouter, UploadFile, File
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from app.services.ocr_service import process_ocr_batch, handle_ocr_remote
import os, json
from app.utils.filename_helper import sanitize_filename
from typing import List
from app.config.base_setting import backend_logger, UPLOAD_FOLDER, OCR_OUTPUT_FOLDER, ARCHIVE_UPLOAD_FOLDER, ARCHIVE_OCR_OUTPUT_FOLDER
from app.jobs.cleanup_job import archive_files

router = APIRouter()

class FilenamePayload(BaseModel):
    filename: str

@router.post("/ocr/remote")
async def run_remote_ocr(payload: List[FilenamePayload]):
    """
    Trigger remote OCR for multiple previously uploaded files.
    """
    try:
        filepaths = []
        filenames = []

        for item in payload:
            sanitized = sanitize_filename(item.filename)

            abs_path = os.path.join(UPLOAD_FOLDER, sanitized)
            if not os.path.exists(abs_path):
                return JSONResponse(status_code=404, content={"message": f"File not found: {sanitized}"})
            
            filepaths.append(abs_path)
            filenames.append(sanitized)

        result = process_ocr_batch(filepaths, output_dir=OCR_OUTPUT_FOLDER)
        return JSONResponse(status_code=200, content=result)

    except Exception as e:
        backend_logger.exception(f"[OCR] Remote OCR Error: {str(e)}")
        return JSONResponse(status_code=500, content={"message": f"OCR Error: {str(e)}"})


@router.post("/ocr/local")
async def run_local_ocr(files: List[UploadFile] = File(...)):
    """
    Handle OCR from local server. currently it's not used yet(call remote_ocr as well).
    """
    try:
        filepaths = []
        filenames = []
        for file in files:
            filepath = os.path.join(UPLOAD_FOLDER, file.filename)
            with open(filepath, "wb") as f:
                f.write(await file.read())

            filename = os.path.basename(filepath)
            filepaths.append(filepath)
            filenames.append(filename)

        backend_logger.info(f"[OCR] Received {len(filepaths)} file(s): {[os.path.basename(p) for p in filepaths]}")
        result = handle_ocr_remote(filepaths, output_dir=OCR_OUTPUT_FOLDER)
        return JSONResponse(status_code=200, content=result)

    except Exception as e:
        backend_logger.exception(f"[OCR] Exception during multi-file OCR: {e}")
        return JSONResponse(status_code=500, content={"message": f"OCR Error: {str(e)}"})

@router.post("/ocr/archive")
async def archive_ocr_outputs():
    try:
        archive_files(source_folder=UPLOAD_FOLDER, target_folder=ARCHIVE_UPLOAD_FOLDER, description="uploaded")
        archive_files(source_folder=OCR_OUTPUT_FOLDER, target_folder=ARCHIVE_OCR_OUTPUT_FOLDER, description="OCR-ed")
        return JSONResponse(status_code=200, content={"message": "Files successfully archived."})
    except Exception as e:
        backend_logger.exception("[ARCHIVE] Archiving failed.")
        return JSONResponse(status_code=500, content={"message": f"Archiving failed: {str(e)}"})
